package com.ktvme.controller;


import com.ktvme.constant.JwtClaimsConstant;
import com.ktvme.dto.UserLoginDTO;
import com.ktvme.entity.User;
import com.ktvme.properties.JwtProperties;
import com.ktvme.result.Result;
import com.ktvme.utils.JwtUtil;
import com.ktvme.vo.UserLoginVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ktvme.service.UserService;
import com.ktvme.dto.UserDTO;

import java.util.HashMap;

@Slf4j
@RestController
@RequestMapping("/BDMobieOps/user")
@Tag(name = "员工相关接口")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping
    @Operation(summary = "新增用户")
    public Result save(@RequestBody UserDTO userDTO){
        log.info("新增用户：{}",userDTO);
        userService.save(userDTO);
        return Result.success();
    }


    @PostMapping("/login")
    @Operation(summary = "员工登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("员工登录：{}", userLoginDTO);
        User user = userService.login(userLoginDTO);
        //登录成功，生成jwt令牌
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        log.info("生成JWT令牌前的claims: {}", claims);
        log.info("生成JWT令牌使用的密钥: {}", jwtProperties.getUserSecretKey());
        log.info("生成JWT令牌使用的时间: {}", jwtProperties.getUserTtl());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    @PostMapping("/logout")
    public Result logout() {
        return Result.success();
    }
}
